using MonoMod.Utils;
using RSCore;
using Terraria.Audio;
using Terraria.GameContent;
using Terraria.ID;

namespace _ReplaceString_.UI.Styles;

public abstract record UIRender(bool Inherit) : UIStyle(Inherit, false)
{
	public static UIRender Debug { get; } = new Debug();
	public static UIRender Click { get; } = new Click();
	public static UIRender Border { get; } = new Border();
	public static UIRender Edge(Direction direction) => new Edge(direction);
}

file record Debug() : UIRender(true)
{
	private static readonly Color[] _colorTable =
	[
		Color.Red, Color.Green, Color.Blue,
		Color.Yellow, Color.Purple, Color.Cyan,
	];

	public override void Draw(UIBase ui)
	{
		ModHelper.DrawBorder(ui.Box, _colorTable[ui.GetHashCode() % _colorTable.Length]);
	}
}

file record Click() : UIRender(false)
{
	private const float DarkenFactor = 1.5f;
	public override void Apply(UIBase ui)
	{
		ui.OnMouseOver += OnMouseOver;
		ui.OnLeftClick += OnLeftClick;
		ui.OnLeftMouseDown += OnLeftMouseDown;
		ui.OnLeftMouseUp += OnLeftMouseUp;
	}

	private void OnLeftMouseUp(UIMouseEvent evt, UIElement listeningElement)
	{
		var ui = (UIBase)listeningElement;
		ui.ForegroundColor *= DarkenFactor;
	}

	private void OnLeftMouseDown(UIMouseEvent evt, UIElement listeningElement)
	{
		var ui = (UIBase)listeningElement;
		ui.ForegroundColor *= 1 / DarkenFactor;
	}

	private void OnLeftClick(UIMouseEvent evt, UIElement listeningElement)
	{
		SoundEngine.PlaySound(SoundID.MenuOpen);
	}

	private void OnMouseOver(UIMouseEvent evt, UIElement listeningElement)
	{
		SoundEngine.PlaySound(SoundID.MenuTick);
	}

	public override void Draw(UIBase ui)
	{
		bool selected = ui.Tag.Has(UITag.Selected);
		var color = selected ? Color.LightGreen : Color.Gold;
		if (ui.IsMouseHovering || selected)
		{
			ModHelper.DrawBorder(ui.Box, color, 2);
		}
	}
}

file record Border() : UIRender(false)
{
	public override void Draw(UIBase ui)
	{
		ModHelper.DrawBorder(ui.Box, ui.ExtraColor, 2);
	}
}

file record Edge(Direction Direction) : UIRender(false)
{
	public override void Draw(UIBase ui)
	{
		var box = Direction.Has(Direction.Inner) ? ui.InnerBox :
			Direction.Has(Direction.Outer) ? ui.OuterBox :
			ui.Box;

		var texture = TextureAssets.MagicPixel.Value;
		if (Direction.Has(Direction.Up))
		{
			Main.spriteBatch.Draw(texture, new Rectangle(box.X, box.Y, box.Width, 2), ui.ForegroundColor);
		}
		if (Direction.Has(Direction.Left))
		{
			Main.spriteBatch.Draw(texture, new Rectangle(box.X, box.Y, 2, box.Height), ui.ForegroundColor);
		}
		if (Direction.Has(Direction.Down))
		{
			Main.spriteBatch.Draw(texture, new Rectangle(box.X, box.Y + box.Height - 2, box.Width, 2), ui.ForegroundColor);
		}
		if (Direction.Has(Direction.Right))
		{
			Main.spriteBatch.Draw(texture, new Rectangle(box.X + box.Width - 2, box.Y, 2, box.Height), ui.ForegroundColor);
		}
	}
}
